# 导入flask
from flask import Flask,request,make_response
from flask_cors import CORS
from database import db
import json

# 实例化对象
app = Flask(__name__)

# 加载配置文件
from config import Config
app.config.from_object(Config)
CORS(app)

# 添加展示
@app.route('/',methods=['POST','GET'])
def newsM():
    # 判断求情方式
    # 添加
    if request.method == "POST":
        # 添加
        # 获取用户输入
        data = json.loads(request.data)
        title = data['title']
        # 返回
        return 'ok'

    else:
        userid = request.args.get('userid')
        name = request.args.get('name')
        return name

import time

#每次请求前钩子
@app.before_request
def before_request():
    # 获取当前url
    url = request.url
    # 获取当前时间戳
    nowtime = time.time()
    sql = "insert into visit(url,stime) values('%s','%d')" % (url,nowtime)
    print(url,nowtime)

# 每次请求后更新结束时间
@app.after_request
def after_request(response):
    # 获取当前url
    url = request.url
    # 获取到当前时间戳
    nowtime = time.time()
    # 根据url去数据库中查询
    sql = "select * from visit where url = '%s' and etime = ''"%(url)
    res = db.findone(sql)
    sql = "update visit set etime='%s' where id = %d " % (nowtime,res['id'])
    return make_response(response)

# 运行
if __name__ == '__main__':
    app.run()

